window.addEventListener(`load`, function () {
    // =========获取元素 start=========
    let tbody = this.document.querySelector(`tbody`)
    // 添加学员按钮
    let btnadd = this.document.querySelector(`.btnadd`)
    // form表单
    let form = this.document.querySelector(`.add-form`)
    // ========以下是模态框信息
    // 模态框==省
    let provinceEle = this.document.querySelector(`[name="province"]`)
    // 模态框==市
    let cityEle = this.document.querySelector(`[name="city"]`)
    // 模态框==县
    let countyEle = this.document.querySelector(`[name="county"]`)
    // 模态框标题
    let addModalLabel = this.document.querySelector(`#addModalLabel`)
    // 模态框确认按钮
    let btnok = this.document.querySelector(`.btnok`)
    // 模态框确认按钮
    let btnreset = this.document.querySelector(`.btnreset`)
    // 模态框==姓名
    let nameEle = this.document.querySelector(`[name="name"]`)
    // 模态框==年龄
    let ageEle = this.document.querySelector(`[name="age"]`)
    // 模态框==手机号
    let phoneEle = this.document.querySelector(`[name="phone"]`)
    // 模态框==期望薪资
    let salaryEle = this.document.querySelector(`[name="salary"]`)
    // 模态框==实际薪资
    let truesalaryEle = this.document.querySelector(`[name="truesalary"]`)
    // 模态框==组号
    let groupEle = this.document.querySelector(`[name="group"]`)
    // 模态框==性别
    let sexs = this.document.querySelectorAll(`[name="sex"]`)


    // =========获取元素 end=========

    // 学员信息动态渲染
    function init() {
        axios({
            url: `/student/list`
        }).then(({ data: { data } }) => {
            // console.log(data);
            let htmlStr = ``
            data.forEach(function (value, index) {
                htmlStr += `<tr>
                                <th scope="row">${index + 1}</th>
                                <td>${value.name}</td>
                                <td>${value.age}</td>
                                <td>${value.sex}</td>
                                <td>${value.group}</td>
                                <td>${value.phone}</td>
                                <td>${value.salary}</td>
                                <td>${value.truesalary}</td>
                                <td>${value.province + value.city + value.county}</td>
                                <td>
                                <button data-id="${value.id}" type="button" class="btn btn-primary btn-sm btnedit">修改</button>
                                <button data-id="${value.id}" type="button" class="btn btn-danger btn-sm btndel">删除</button>
                                </td>
                            </tr>`
            })
            tbody.innerHTML = htmlStr
        })
    }
    init()

    // 学员信息添加
    // 点击添加学员弹出模态框
    btnadd.addEventListener(`click`, function () {
        // console.log(`我是添加按钮`);
        // 弹出模态框
        $('#addModal').modal('show')
        addModalLabel.innerHTML = `录入新学员`
        btnok.innerHTML = `确认添加`
        btnreset.click()
    })

    // 表单验证
    function student() {
        return {
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空',
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度2~10位'
                        }
                    }
                },
                age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空',
                        },
                        greaterThan: {
                            value: 18,
                            message: '年龄不能小于18岁'
                        },
                        lessThan: {
                            value: 60,
                            message: '年龄不能超过60岁'
                        }
                    }
                },
                sex: {
                    validators: {
                        choice: {
                            min: 1,
                            max: 1,
                            message: '请选择性别'
                        }
                    }
                },
                group: {
                    validators: {
                        notEmpty: {
                            message: '组号不能为空',
                        },
                        regexp: {
                            regexp: /^\d{1,2}$/,
                            message: '请选择有效的组号'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空',
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请填写有效的手机号'
                        }
                    }
                },
                salary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '期望薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '期望薪资不能高于100000'
                        }
                    }
                },
                truesalary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '实际薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '实际薪资不能高于100000'
                        }
                    }
                },
                province: {
                    validators: {
                        notEmpty: {
                            message: '省份必填',
                        },
                    }
                },
                city: {
                    validators: {
                        notEmpty: {
                            message: '市必填',
                        },
                    }
                },
                county: {
                    validators: {
                        notEmpty: {
                            message: '县必填',
                        },
                    }
                },
            }
        }
    }

    // =========获取省=========
    axios({
        url: `/geo/province`
    }).then(res => {
        // console.log(res.data);
        let htmlStr = `<option selected value="">--省--</option>`
        res.data.forEach(function (value, index) {
            htmlStr += `<option value="${value}">${value}</option>`
        })
        provinceEle.innerHTML = htmlStr
    })

    let cityDone, countDone
    // =========获取省的市=========
    provinceEle.addEventListener(`change`, function () {
        let pname = provinceEle.value
        if (!pname) {
            cityEle.innerHTML = `<option selected value="">--市--</option>`
            countyEle.innerHTML = `<option selected value="">--县--</option>`
            return
        }
        axios({
            url: `/geo/city`,
            params: { pname }
        }).then(res => {
            // console.log(res.data);
            let htmlStr = `<option selected value="">--市--</option>`
            res.data.forEach(function (value, index) {
                htmlStr += `<option value="${value}">${value}</option>`
            })
            cityEle.innerHTML = htmlStr
            cityDone = true
        })
    })

    // =========获取市的县=========
    cityEle.addEventListener(`change`, function () {
        let pname = provinceEle.value
        let cname = cityEle.value
        if (!cname) {
            countyEle.innerHTML = `<option selected value="">--县--</option>`
            return
        }
        axios({
            url: `/geo/county`,
            params: { pname, cname }
        }).then(res => {
            // console.log(res.data);
            let htmlStr = `<option selected value="">--县--</option>`
            res.data.forEach(function (value, index) {
                htmlStr += `<option value="${value}">${value}</option>`
            })
            countyEle.innerHTML = htmlStr
            countDone = true
        })
    })

    // =========添加功能=========
    $('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
        e.preventDefault();
        let formdata = new FormData(form)
        let data = {}
        formdata.forEach(function (value, key) {
            // console.log(key, value);
            data[key] = value
        })
        if (addModalLabel.innerHTML == `录入新学员`) {
            axios({
                url: `/student/add`,
                method: `POST`,
                data: data
            }).then(res => {
                // console.log(res);
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    $('#addModal').modal('hide')
                    init()
                }
            })
        } else {
            data.id = editid
            axios({
                url: `/student/update`,
                method: `put`,
                data: data
            }).then(res => {
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    $('#addModal').modal('hide')
                    init()
                }
            })
        }
    })

    // =========删除功能=========
    tbody.addEventListener(`click`, function (e) {
        if (e.target.classList.contains(`btndel`)) {
            // console.log(`我是删除按钮`);
            let id = e.target.dataset.id
            // console.log(id);
            axios({
                url: `/student/delete`,
                method: `DELETE`,
                params: { id }
            }).then(res => {
                // console.log(res);
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    init()
                }
            })
        }
    })

    let editid
    // =========编辑功能=========
    tbody.addEventListener(`click`, function (e) {
        if (e.target.classList.contains(`btnedit`)) {
            cityDone = false
            countDone = false
            // console.log(`我是编辑按钮`);
            // 点击编辑弹出模态框
            $('#addModal').modal('show')
            addModalLabel.innerHTML = `编辑学员信息`
            btnok.innerHTML = `确认编辑`

            // 数据回填
            // 获取id
            let id = e.target.dataset.id
            editid = id
            // console.log(id);
            axios({
                url: `/student/one`,
                params: { id }
            }).then(({ data: { data } }) => {
                // console.log(data);
                nameEle.value = data.name
                ageEle.value = data.age
                phoneEle.value = data.phone
                salaryEle.value = data.salary
                truesalaryEle.value = data.truesalary
                groupEle.value = data.group
                // 性别
                data.sex == `男` ? sexs[0].checked = true : sexs[1].checked = true
                // 省
                provinceEle.value = data.province
                // 市
                cityEle.innerHTML = `<option selected value="">${data.city}</option>`
                // 县
                countyEle.innerHTML = `<option selected value="">${data.county}</option>`

                // 市触发
                let ev = document.createEvent(`HtmlEvents`)
                ev.initEvent(`change`, true, true)
                provinceEle.dispatchEvent(ev)
                let tid = setInterval(() => {
                    if (cityDone) {
                        cityEle.value = data.city
                        clearInterval(tid)
                        // 县触发
                        let ev1 = document.createEvent(`HtmlEvents`)
                        ev1.initEvent(`change`, true, true)
                        cityEle.dispatchEvent(ev1)
                        tid = setInterval(() => {
                            if (countDone) {
                                countyEle.value = data.county
                                clearInterval(tid)
                            }
                        }, 100);
                    }
                }, 100);
            })
        }
    })
})